package com.darwin.darwinDll.analyze
{
	import com.darwin.darwinDll.core.DllItem;
	
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.Loader;
	import flash.events.Event;
	import flash.events.TimerEvent;
	import flash.utils.ByteArray;
	import flash.utils.Dictionary;
	import flash.utils.Timer;

	/**
	 * 图片解析器 
	 * @author vanCopper
	 * 
	 */	
	public class ImgAnalyze implements IAnalyze
	{
		private static const DELAY_TIME:int = 50;
		private var _timer:Timer;
		
		public function ImgAnalyze()
		{
			_timer = new Timer(DELAY_TIME);
			_timer.addEventListener(TimerEvent.TIMER,onTimer);
			_timer.start();
		}
		
		private function onTimer(e:TimerEvent):void
		{
			for(var loader:* in _dllItemDic)
			{
				var byteArray:ByteArray = _byteArrayDic[loader];
				if(byteArray != null)
				{
					loader.loadBytes(byteArray);
					break;
				}
			}
		}
		
		private var _dllItemDic:Dictionary = new Dictionary();
		private var _compFnDic:Dictionary = new Dictionary();
		private var _bitmapDataDic:Dictionary = new Dictionary();
		private var _byteArrayDic:Dictionary = new Dictionary();
		public function analyze(byteArray:ByteArray, dllItem:DllItem, compFn:Function):void
		{
			var loader:Loader=new Loader();    
			dllItem.data = byteArray;
			_byteArrayDic[loader] = byteArray;
//			loader.loadBytes(byteArray);//读取ByteArray    
			loader.contentLoaderInfo.addEventListener(Event.COMPLETE, bytesComplete); 
			_dllItemDic[loader] = dllItem;
			_compFnDic[loader] = compFn;
		}
		
		private function bytesComplete(e:Event):void
		{
			var targetLoader:Loader = e.target.loader;// as Loader;
			var dllItem:DllItem = _dllItemDic[targetLoader];
			var func:Function = _compFnDic[targetLoader];
			var bitmap:Bitmap = Bitmap(e.target.content);//读取Bitmap
			dllItem.result = bitmap.bitmapData.clone();
			_bitmapDataDic[dllItem.name] = bitmap.bitmapData;
			targetLoader.contentLoaderInfo.removeEventListener(Event.COMPLETE, bytesComplete);
			dllItem.status = DllItem.STATUS_LOADED;
			func(dllItem);
			delete _byteArrayDic[targetLoader];
			delete _dllItemDic[targetLoader];
			delete _compFnDic[targetLoader];
		}
		
		/**
		 * 获取图片资源 返回bitmap 
		 * @param key
		 * @param subKey
		 * @return 
		 * 
		 */		
		public function getData(key:String, subKey:String):*
		{
			var bitmapData:BitmapData = _bitmapDataDic[key] as BitmapData;
			if(bitmapData == null)
			{
				bitmapData = _bitmapDataDic[key + "$" + subKey];
			}
			return bitmapData;
		}
		
		public function getDataList():Dictionary
		{
			return _bitmapDataDic;
		}
		
	}
}